package app.nbdevices.utils;

import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.http.HttpResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SingleReg {
    public static void main(String[] args) throws Exception {
        InputStream iFile=new FileInputStream(new File("E:/re.xls"));
        Workbook wb = new HSSFWorkbook(iFile);
        Sheet sheet = wb.getSheetAt(0);
        int rowNum=sheet.getLastRowNum();

        HttpsUtil httpsUtil = new HttpsUtil();
        httpsUtil.initSSLConfigForTwoWay();

        // Authentication.get token
        String accessToken = login(httpsUtil);
        List<String> devIds=new ArrayList<>();
        devIds.add("47c2d4d1-7d96-48ed-8a32-730d57192037");
        devIds.add("58e8d06d-7ed1-4d3f-9f54-3816f3cbf803");
        devIds.add("5b2b691c-f935-4a15-af09-e7740074ea21");
        devIds.add("e4e38f68-4d8e-4706-b131-869d52f229f6");
        devIds.add("3f0ea04f-2019-48af-89f6-ca57220d96d4");
        devIds.add("c991e28b-3ae6-48c3-ac45-d6679ce7027d");
        devIds.add("95aad3cb-8c31-4e49-b83a-69524e68f868");
        devIds.add("7fa21deb-c732-4332-9476-31bdc3552cef");
        devIds.add("d4f3b909-41cf-4e39-b9d1-7c4451a0eae3");
        devIds.add("dafc82a0-535f-4bce-b776-5ace2f35a512");
      //  String devId="";
        for(String id:devIds){
            cmdTest(accessToken,httpsUtil,id);
        }
 //   cmdTest(accessToken,httpsUtil,"f6a7fe50-6e38-426f-aec7-80b2f309d3df");
//        int count=0;
//        List<String> devIds=new ArrayList<>();
//        String devId=null;
//        for(int i=1;i<11;i++){
//            System.out.println(sheet.getRow(i).getCell(0).toString()+" "+sheet.getRow(i).getCell(1).toString().substring(1));
//            devId=reg(sheet.getRow(i).getCell(1).toString(),accessToken,sheet.getRow(i).getCell(0).toString(),httpsUtil);
//            devIds.add(devId);
//        //    cmdTest(accessToken,httpsUtil,devId);
//            count++;
//        }
//
//        accessToken=login(httpsUtil);
//        for(String id:devIds){
//            devDel(id,accessToken,httpsUtil);
//        }
//
//        System.out.println(count);
    }
    public static void cmdTest(String accessToken,HttpsUtil httpsUtil,String deviceId) throws Exception {

        String urlCreateDeviceCommand = Constant.CREATE_DEVICE_CMD;
        String appId = Constant.APPID;

        String callbackUrl=Constant.CALLBACK_BASE_URL;

        Integer expireTime = 0;
        Integer maxRetransmit = 3;

        String serviceId="doorOper";
        String method="doorCmd";

        String cmd;

        String c="{\"addrId\":\"VDAwMDAx\",\"cmdData\":\"AQBV\"}";
        ObjectNode paras = JsonUtil.convertObject2ObjectNode(c);

        Map<String, Object> paramCommand = new HashMap<>();
        paramCommand.put("serviceId", serviceId);
        paramCommand.put("method", method);
        paramCommand.put("paras", paras);

        Map<String, Object> paramCreateDeviceCommand = new HashMap<>();
        paramCreateDeviceCommand.put("deviceId", deviceId);
        paramCreateDeviceCommand.put("command", paramCommand);
        paramCreateDeviceCommand.put("callbackUrl", callbackUrl);
        paramCreateDeviceCommand.put("expireTime", expireTime);
        paramCreateDeviceCommand.put("maxRetransmit", maxRetransmit);

        String jsonRequest = JsonUtil.jsonObj2Sting(paramCreateDeviceCommand);

        System.out.println(jsonRequest);

        Map<String, String> header = new HashMap<>();
        header.put(Constant.HEADER_APP_KEY, appId);
        header.put(Constant.HEADER_APP_AUTH, "Bearer" + " " + accessToken);

        HttpResponse responseCreateDeviceCommand = httpsUtil.doPostJson(urlCreateDeviceCommand, header, jsonRequest);

        String responseBody = httpsUtil.getHttpResponseBody(responseCreateDeviceCommand);

        System.out.println("CreateDeviceCommand, response content:");
        System.out.println(responseCreateDeviceCommand.getStatusLine());
        System.out.println(responseBody);
        System.out.println();
    }
    public static String reg(String nodeId, String accessToken, String devName, HttpsUtil httpsUtil){
        //Please make sure that the following parameter values have been modified in the Constant file.
        String appId = Constant.APPID;
        String urlRegisterDirectConnectedDevice = Constant.REGISTER_DIRECT_CONNECTED_DEVICE;

        //please replace the verifyCode and nodeId and timeout, when you call this interface.
        String verifyCode = nodeId;
        Integer timeout = 0;

        //please replace the following parameter values, when you call this interface.
        //And those parameter values must be consistent with the content of profile that have been preset to IoT platform.
        //The following parameter values of this demo are use the watermeter profile that already initialized to IoT platform.
        String manufacturerId= "56095d1545eb450cba2b945de6c3794b";
        String manufacturerName = "yfkj";
        String deviceType = "DoorLock";
        String model = "DOORV11";
        String protocolType = "LWM2M";
        String name=devName;

        Map<String, Object> paramDeviceInfo = new HashMap<>();
        paramDeviceInfo.put("name",name);
        paramDeviceInfo.put("manufacturerId", manufacturerId);
        paramDeviceInfo.put("manufacturerName", manufacturerName);
        paramDeviceInfo.put("deviceType", deviceType);
        paramDeviceInfo.put("model", model);
        paramDeviceInfo.put("protocolType", protocolType);


        Map<String, Object> paramReg = new HashMap<>();
        paramReg.put("verifyCode", verifyCode.toUpperCase());
        paramReg.put("nodeId", nodeId.toUpperCase());
        paramReg.put("deviceInfo", paramDeviceInfo);
        paramReg.put("timeout", timeout);

        String jsonRequest = JsonUtil.jsonObj2Sting(paramReg);

        Map<String, String> header = new HashMap<>();
        header.put(Constant.HEADER_APP_KEY, appId);
        header.put(Constant.HEADER_APP_AUTH, "Bearer" + " " + accessToken);

        StreamClosedHttpResponse responseRegisterDirectConnectedDevice = httpsUtil.doPostJsonGetStatusLine(urlRegisterDirectConnectedDevice, header, jsonRequest);

        System.out.println("RegisterDirectConnectedDevice, response content:");
        System.out.println(responseRegisterDirectConnectedDevice.getStatusLine());
        String devid=responseRegisterDirectConnectedDevice.getContent().substring(13,49);
        System.out.println(devid);
        modName(devid,accessToken,name,httpsUtil);
        return devid;
    }
    public static void modName(String deviceId,String accessToken,String name,HttpsUtil httpsUtil){
//Please make sure that the following parameter values have been modified in the Constant file.
        String appId = Constant.APPID;

        //please replace the deviceId, when you call this interface.
      //  String deviceId = "3abc6184-9969-4bb6-95d9-f8646a3511ad";
        String urlModifyDeviceInfo = Constant.MODIFY_DEVICE_INFO + "/" + deviceId;

        //please replace the following parameter values, when you call this interface.
       // String name = "demo01";
        String region = "China";

        Map<String, Object> paramModifyDeviceInfo = new HashMap<>();
        paramModifyDeviceInfo.put("name", name);
        paramModifyDeviceInfo.put("region", region);

        String jsonRequest = JsonUtil.jsonObj2Sting(paramModifyDeviceInfo);

        Map<String, String> header = new HashMap<>();
        header.put(Constant.HEADER_APP_KEY, appId);
        header.put(Constant.HEADER_APP_AUTH, "Bearer" + " " + accessToken);

        StreamClosedHttpResponse responseModifyDeviceInfo = httpsUtil.doPutJsonGetStatusLine(urlModifyDeviceInfo,
                header, jsonRequest);

        System.out.println("ModifyDeviceInfo, response content:");
        System.out.println(responseModifyDeviceInfo.getStatusLine());
        System.out.println(responseModifyDeviceInfo.getContent());
        System.out.println();
    }
    public static void devDel(String deviceId,String accessToken,HttpsUtil httpsUtil) throws Exception {
        String appId = Constant.APPID;

        //please replace the deviceId, when you call this interface.
        String urlDeleteDirectConnectedDevice = Constant.DELETE_DIRECT_CONNECTED_DEVICE + "/" +deviceId;

        Map<String, String> header = new HashMap<>();
        header.put(Constant.HEADER_APP_KEY, appId);
        header.put(Constant.HEADER_APP_AUTH, "Bearer" + " " + accessToken);

        StreamClosedHttpResponse responseDeleteDirectConnectedDevice = httpsUtil.doDeleteWithParasGetStatusLine(urlDeleteDirectConnectedDevice, null, header);

        System.out.println("DeleteDirectConnectedDevice, response content:");
        System.out.println(responseDeleteDirectConnectedDevice.getStatusLine());
        System.out.println(responseDeleteDirectConnectedDevice.getContent());
        System.out.println();
    }
    public static String login(HttpsUtil httpsUtil) throws Exception {

        String appId = Constant.APPID;
        String secret = Constant.SECRET;
        String urlLogin = Constant.APP_AUTH;

        Map<String, String> paramLogin = new HashMap<>();
        paramLogin.put("appId", appId);
        paramLogin.put("secret", secret);

        StreamClosedHttpResponse responseLogin = httpsUtil.doPostFormUrlEncodedGetStatusLine(urlLogin, paramLogin);

        System.out.println("app auth success,return accessToken:");
        System.out.println(responseLogin.getStatusLine());
        System.out.println(responseLogin.getContent());
        System.out.println();

        Map<String, String> data = new HashMap<>();
        data = JsonUtil.jsonString2SimpleObj(responseLogin.getContent(), data.getClass());
        return data.get("accessToken");
    }
}
